//
//  ZYPersonManagerViewController.m
//  ZYOils
//
//  Created by 段新瑞 on 2019/9/24.
//  Copyright © 2019 Mr.Xr. All rights reserved.
//

#import "ZYPersonManagerViewController.h"

#import "ZYPersonManagerAddPersonTableViewController.h"

#import "ZYPersonManagerTableViewCell.h"
#import "ZYPersonManagerAddPersonTableViewCell.h"
#import "XRRefreshHeader.h"
#import "XRRefreshFooter.h"
#import "ZYGetUserByManagerModel.h"
#import "ZYBillListViewController.h"


@interface ZYPersonManagerViewController () <SWTableViewCellDelegate, UITableViewDelegate, UITableViewDataSource>

/// 🙄🙄🙄
@property(nonatomic, strong) UITableView *tableView;

/// 店员列表
@property (nonatomic, strong) NSMutableArray *personLists;

@property (nonatomic) NSInteger page;

@end

@implementation ZYPersonManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"人员管理";
    
    self.page = 1;
    
    [self customUI];
}

- (void)customUI {
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(0);
    }];
    
     [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ZYPersonManagerAddPersonTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ZYPersonManagerAddPersonTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ZYPersonManagerTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ZYPersonManagerTableViewCell class])];
    
    @weakify(self)
    self.tableView.mj_header = [XRRefreshHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self getNewData];
    }];
    
    self.tableView.mj_footer = [XRRefreshFooter footerWithRefreshingBlock:^{
        @strongify(self)
        [self getMoreData];
    }];
    
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer.hidden = YES;
}

- (void)getNewData {
    NSDictionary *dict = @{@"managerId": STR(ZYUserInfoModel.sharedInfoModel.userModel.userId),
                           @"page": STR_LONG(self.page),
                           @"size": @"10"};
    // [ZYHud showLoadingText:@""];
    [[DataManager manager] postFindPersonParam:dict block:^(XRCommonModel *model, NSError *error) {
        [self.tableView.mj_header endRefreshing];
        
        if (model.isSuccess) {
            // self.tableView.mj_footer.hidden = NO;
            self.page = 1;
            self.personLists = [ZYGetUserByManagerModel mj_objectArrayWithKeyValuesArray:model.data];
            /**
             if (self.personLists.count < 10) {
             [self.tableView.mj_footer endRefreshingWithNoMoreData];
             } else {
             [self.tableView.mj_footer resetNoMoreData];
             }
            */
            [self.tableView reloadData];
        } else {
            if (![LBLimitInput isEmpty:model.error]) {
                [ZYHud showErrorText:model.error];
            }
        }
    }];
}

- (void)getMoreData {
    NSDictionary *dict = @{@"managerId": ZYUserInfoModel.sharedInfoModel.userModel.managerId,
                           @"page": [NSString stringWithFormat:@"%ld", self.page],
                           @"size": @"100"};
    [ZYHud showLoadingText:@""];
    [[DataManager manager] postFindPersonParam:dict block:^(XRCommonModel *model, NSError *error) {
        [ZYHud hideHud];
        [self.tableView.mj_footer endRefreshing];
        if (model.isSuccess) {
            self.page += 1;
            [self.personLists addObjectsFromArray:[ZYGetUserByManagerModel mj_objectArrayWithKeyValuesArray:model.data]];
            if ([ZYGetUserByManagerModel mj_objectArrayWithKeyValuesArray:model.data].count < 10) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.tableView.mj_footer resetNoMoreData];
            }
            [self.tableView reloadData];
        } else {
            if (![LBLimitInput isEmpty:model.error]) {
                [ZYHud showErrorText:model.error];
            }
        }
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return self.personLists.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZYPersonManagerAddPersonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYPersonManagerAddPersonTableViewCell class])];
        return cell;
    } else {
        ZYPersonManagerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYPersonManagerTableViewCell class])];
        cell.rightUtilityButtons = [self rightButtons];
        cell.delegate = self;
        cell.model = self.personLists[indexPath.row];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 120;
    } else {
        return 138;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZYPersonManagerAddPersonTableViewController *controller = [[UIStoryboard storyboardWithName:@"ZYPersonManagerAddPersonTableViewController" bundle:nil] instantiateInitialViewController];
        @weakify(self)
        [controller.subject subscribeNext:^(NSString *state) {
            @strongify(self)
            if ([state isEqualToString:@"add"]) {
                [self getNewData];
            }
        }];
        controller.title = @"添加店员";
        [self.navigationController pushViewController:controller animated:YES];
    } else if (indexPath.section == 1) {
        ZYBillListViewController *controller = [ZYBillListViewController new];
        ZYGetUserByManagerModel *model = self.personLists[indexPath.row];
        controller.userId = model.userId;
        [self.navigationController pushViewController:controller animated:YES];
    }
}

#pragma mark - SWTableViewDelegate
- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index {
    NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
    ZYGetUserByManagerModel *model = self.personLists[cellIndexPath.row];
    switch (index) {
        case 0: {
            ZYPersonManagerAddPersonTableViewController *controller = [[UIStoryboard storyboardWithName:@"ZYPersonManagerAddPersonTableViewController" bundle:nil] instantiateInitialViewController];
            controller.title = @"修改信息";
            controller.state = PersonStateChange;
            controller.model = model;
            @weakify(self)
            [controller.subject subscribeNext:^(NSString *state) {
                @strongify(self)
                if ([state isEqualToString:@"change"]) {
                    [self.tableView reloadData];
                }
            }];
            [self.navigationController pushViewController:controller animated:YES];
            [cell hideUtilityButtonsAnimated:YES];
            break;
        }
        case 1:
        {
            [ZYHud showLoadingText:@""];
            NSDictionary *dict = @{@"userId": model.userId};
            [[DataManager manager] postDeleteUserParam:dict block:^(XRCommonModel *model, NSError *error) {
                [ZYHud hideHud];
                if (model.isSuccess) {
                    [self.personLists removeObjectAtIndex:cellIndexPath.row];
                    [self.tableView deleteRowsAtIndexPaths:@[cellIndexPath]
                            withRowAnimation:UITableViewRowAnimationLeft];
                } else {
                    if (![LBLimitInput isEmpty:model.error]) {
                        [ZYHud showErrorText:model.error];
                    }
                }
            }];
            break;
        }
        default: break;
    }
}

- (NSArray *)rightButtons
{
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:COLORHEX(@"898b99")
                                                title:@"编辑"];
    [rightUtilityButtons sw_addUtilityButtonWithColor:COLORHEX(@"d72b2c")
                                                title:@"删除"];

    return rightUtilityButtons;
}

- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell {
    
    // allow just one cell's utility button to be open at once
    return YES;
}

- (BOOL)swipeableTableViewCell:(SWTableViewCell *)cell canSwipeToState:(SWCellState)state {
    
    switch (state) {
        case 1:
            // set to NO to disable all left utility buttons appearing
            return NO;
            break;
        case 2:
            // set to NO to disable all right utility buttons appearing
            return YES;
            break;
        default:
            break;
    }
    
    return YES;
}


- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = BACKGROUNDCOLOR;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
        view.backgroundColor = [UIColor clearColor];
        _tableView.tableHeaderView = view;
    }
    return _tableView;
}


- (NSMutableArray *)personLists {
    if (!_personLists) {
        _personLists = [[NSMutableArray alloc] init];
    }
    return _personLists;
}

@end
